package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.cache.store.UserStore;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.HomePageEntity;
import com.zw.yzk.kabu.data.network.service.HomePageService;
import com.zw.yzk.kabu.data.network.task.HomePageTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class HomePageRepository extends CommonRepository {

    private int totalCount;

    @Inject
    public HomePageRepository() {
        totalCount = HomePageTask.DEFAULT_COS_COUNT_PER_PAGE;
    }


    @Override
    protected Observable connectServer(Task task) {
        HomePageService service = ServiceGenerator.createService(HomePageService.class);
        HomePageTask homePageTask = (HomePageTask) addToken(task);
        String ownerId;
        if(homePageTask.ownerId == 0) {
            ownerId = null;
        } else {
            ownerId = String.valueOf(homePageTask.ownerId);
        }

        if (homePageTask.start > totalCount) {
            HomePageEntity entity = new HomePageEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.total = totalCount;

            return Observable.just(entity);
        } else {
            return service.getHomePageInfo(
                    ownerId,
                    homePageTask.ownerName,
                    homePageTask.userId,
                    homePageTask.accessToken,
                    homePageTask.lastId,
                    homePageTask.size);
        }
    }

    @Override
    protected Func1<HomePageEntity, Observable> getServerData() {
        return new Func1<HomePageEntity, Observable>() {
            @Override
            public Observable call(HomePageEntity entity) {
                totalCount = entity.result.total;
                updateUser(entity);
                return Observable.just(entity);
            }
        };
    }

    /**
     * 更新user信息
     *
     * @param entity
     */
    private void updateUser(HomePageEntity entity) {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null) {
            return;
        }
        //TODO 如果拉取的是个人信息那么进行更新
        new UserStore().updateUserInfo(user);
    }
}
